package com.sgj.gulimall.product.service.impl;

import com.sgj.gulimall.product.entity.SkuImagesEntity;
import com.sgj.gulimall.product.entity.SpuInfoDescEntity;
import com.sgj.gulimall.product.service.*;
import com.sgj.gulimall.product.vo.SkuItemVo;
import com.sgj.gulimall.product.vo.SkuItemVo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.product.dao.SkuInfoDao;
import com.sgj.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    public static final String CONSTANT = "0";

    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private SpuInfoDescService descService;

    @Autowired
    private AttrGroupService groupService;

    @Autowired
    private SkuSaleAttrValueService attrValueService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String catalogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");

        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(item -> item.eq("sku_id", key).or().like("sku_name", key));
        }

        if (StringUtils.isNotEmpty(catalogId) && !CONSTANT.equals(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }

        if (StringUtils.isNotEmpty(brandId) && !CONSTANT.equals(catalogId)) {
            wrapper.eq("brand_id", brandId);
        }

        if (StringUtils.isNotEmpty(min)) {
            wrapper.ge("price", min);
        }

        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                // 最大值不为0才进行拼接条件
                if (bigDecimal.compareTo(new BigDecimal(CONSTANT)) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo vo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // sku 基本信息获取
            SkuInfoEntity info = baseMapper.selectById(skuId);
            vo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            // spu 销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVoList = attrValueService.getSaleAttrsBySpuId(res.getSpuId());
            vo.setSaleAttrs(saleAttrVoList);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            // spu 介绍信息
            SpuInfoDescEntity desc = descService.getById(res.getSpuId());
            vo.setDesc(desc);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            // spu 规格参数信息
            List<SpuItemAttrGroupVo> groupVoList = groupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            vo.setGroupAttrs(groupVoList);
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // sku 图片信息
            List<SkuImagesEntity> imageList = imagesService.getImagesBySkuId(skuId);
            vo.setImages(imageList);
        }, executor);

        // 等待所有异步执行完成
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture).get();

        return vo;
    }
}